package pixivPc.task;

import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;

import pixivPc.http.RequestUtil;
import pixivPc.http.RequestUtil.SendType;
import pixivPc.ui.Panel;

/**
 * 主页Task
 * 
 * @author wangm
 *
 */
public class IndexTask extends BaseTask {

	/**
	 * login页面url
	 */
	public static final String url = "https://accounts.pixiv.net/login?lang=ja&source=pc&view_type=page&ref=wwwtop_accounts_index";

	/**
	 * postKey匹配用正则
	 */
	private static final String pattern = "postKey\\s*\":\"([^\\\"]+)\"";

	/**
	 * 主页Task
	 */
	public IndexTask() {
		// 打开login页面
		super(url, "", "", SendType.GET);
	}

	@Override
	protected void process(Panel panel, InputStream in) {

		// 主界面设定
		TextField id = new TextField(10);
		TextField passwd = new TextField(10);
		TextField postKey = new TextField(30);
		postKey.setEditable(false);
		passwd.setEchoChar('*');

		// 读取html 获取并设定postkey
		String html = RequestUtil.readHtml(in);
		System.out.println("+++++++++" + html.indexOf("postKey"));
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(html);
		if (m.find()) {
			String key = m.group(1);
			System.out.println("postKey\t" + key);
			postKey.setText(key);
		}

		panel.add(id);
		panel.add(passwd);
		panel.add(postKey);
		// 主界面设定结束

		// 登录按钮设定
		ActionListener listener = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println(id.getText() + "\t" + passwd.getText());
				// 创建登录task
				LoginTask login = new LoginTask(id.getText(), passwd.getText(), postKey.getText());
				panel.getMain().runTask("indexPic", login);
				// 跳转主页面
				panel.getMain().runTask("indexPic", new TestTask("https://www.pixiv.net/", url, "", sendType.GET));
			}
		};
		JButton button = new JButton("OK");
		button.addActionListener(listener);
		panel.add(button);
		// 登录按钮设定结束

		// 登录页面随机图片浏览
		panel.getMain().runTaskWithNewPanel("indexPic", new IndexPicTask());
	}

}
